package com.googlecode.jfxgap;

import javafx.animation.FadeTransition;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;

/**
 * Desktop splash class. Handle application splash screen.
 * Inspired by https://gist.github.com/1588531
 * @author Cyril Joui
 */
public class DesktopSplash {
	private Pane splashLayout;
	private ProgressBar loadProgress;
	private Label progressText;
	private Stage initStage;

	/**
	 * Splash image.
	 */
	private Image image;

	/**
	 * Constructor.
	 */
	public DesktopSplash() {
		image = null;
		try {
			// Try to load splash
			image = new Image(getClass().getResourceAsStream("/splash.png"));
		} catch (NullPointerException e) {
			// Default cordova image
			image = new Image(getClass().getResourceAsStream(
					"/splash-cordova.png"));
		}

		ImageView splash = new ImageView(image);
		loadProgress = new ProgressBar();
		loadProgress.setPrefWidth(image.getWidth());
		progressText = new Label("Loading . . .");
		splashLayout = new VBox();
		splashLayout.getChildren().addAll(splash, loadProgress, progressText);
		progressText.setAlignment(Pos.CENTER);
		splashLayout
				.setStyle("-fx-padding: 2; -fx-background-color: white; -fx-border-width:2; -fx-border-color: linear-gradient(to bottom, black, derive(black, 50%));");
		splashLayout.setEffect(new DropShadow());
	}

	public void show(Stage initStage) {
		this.initStage = initStage;
		Scene splashScene = new Scene(splashLayout);
		initStage.initStyle(StageStyle.UNDECORATED);
		final Rectangle2D bounds = Screen.getPrimary().getBounds();
		initStage.setScene(splashScene);
		initStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - image.getWidth()
				/ 2);
		initStage.setY(bounds.getMinY() + bounds.getHeight() / 2
				- image.getHeight() / 2);
		initStage.show();
	}

	public void destroy(final EventHandler<ActionEvent> eventHandler) {
		getLoadProgress().progressProperty().unbind();
		getLoadProgress().setProgress(1);
		progressText.setText("Loaded !");
		// mainStage.setIconified(false);
		initStage.toFront();
		FadeTransition fadeSplash = new FadeTransition(Duration.seconds(1.2),
				splashLayout);
		fadeSplash.setFromValue(1.0);
		fadeSplash.setToValue(0.0);
		fadeSplash.setOnFinished(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent e) {
				initStage.hide();
				eventHandler.handle(e);
			}
		});
		fadeSplash.play();
	}

	/**
	 * @return the loadProgress
	 */
	protected ProgressBar getLoadProgress() {
		return loadProgress;
	}

}
